package com.study.lu.thread.producercustomer.newjdk;

import com.study.lu.thread.producercustomer.Food;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <b>System：</b>incommonusefactory<br/>
 * <b>Title：</b>FoodFactoryByLock.java<br/>
 * <b>Description：</b> 对功能点的描述<br/>
 * <b>@author： </b>raoluping<br/>
 * <b>@date：</b>2017/12/23 16:59<br/>
 * <b>@version：</b> 1.0.0.0 <br/>
 * <b>Copyright (c) 2017 ASPire Tech.</b>
 */
public class FoodFactoryByLock {
    private Lock lock = new ReentrantLock();

    // 生产者生产的东西是否达到上限 即控制生产者是否等待和被唤醒
    private Condition producerCondition = lock.newCondition();

    // 消费者是否还有东西可以消费 即控制消费者是否等待和被唤醒
    private Condition customerCondition = lock.newCondition();


    private List<Food> foods = new ArrayList<>();
    private final static int FOOD_MAX_SIZE = 1;

    public void customFood() throws InterruptedException {
        lock.lock();
        try {
            // 食物没了
            while (foods.size() <= 0) {
                try {
                    // System.out.println("目前没有食物，需要等待生产者生产");
                    // 说明食物已经没了，需要等待生产者去生产
                    customerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Food food = foods.get(0);

            foods.remove(food);
            System.out.println("消费者消费了：食物  " + food.getFoodName() + " 数量" + food.getQty());
            // Thread.sleep(1000);
            // 消费者消费了食物，那么生产者就又可以开始生产了
            producerCondition.signal();
        } finally {
            lock.unlock();
        }



    }

    public void producerFood() throws InterruptedException {
        lock.lock();
        try {
            while (FOOD_MAX_SIZE <= foods.size()) {
                try {
                    // System.out.println("厂库存货已达上限。不能再进行生产食物");
                    producerCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Thread.sleep(2000);
            Food food = new Food("苹果", 1111);
            foods.add(food);
            System.out.println("生产者生产了一份食物");

            customerCondition.signal();
        } finally {
            lock.unlock();
        }



    }


}
